<template>
  <div>
    <div class="page-comon-header">
      <div class="left">
        <label class="font14 margin-r-5">筛选</label>
        <el-select
          v-model="search.type"
          clearable
          @change="handleTypeChange"
          placeholder="请选择预警类型">
          <el-option
            v-for="item in warningTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="right">
        <div class="right-item text-center">
          <span class="font28 padding-b-10">{{ warningStats.total }}</span>
          <p class="font14 txt-info">总预警数</p>
        </div>
        <div class="right-item text-center">
          <span class="font28 padding-b-10 warning-text">{{ warningStats.unprocessed }}</span>
          <p class="font14 txt-info">未处理</p>
        </div>
        <div class="right-item text-center">
          <span class="font28 padding-b-10 success-text">{{ warningStats.processed }}</span>
          <p class="font14 txt-info">已处理</p>
        </div>
      </div>
    </div>
    
    <div class="page-search-bar">
      <div class="left">
        <label class="font14 margin-r-5">搜索</label>
        <el-input
          placeholder="输入产品名称"
          icon="search"
          v-model="search.keyword"
          @change="handleKeywordChange"
          :on-icon-click="handleSearch">
        </el-input>
      </div>
      <div class="right">
        <el-button type="primary" @click="handleRefresh">刷新预警</el-button>
        <el-button type="success" @click="handleExport">导出报表</el-button>
      </div>
    </div>
    
    <el-table
      :data="tableData"
      style="width: 100%"
      :row-class-name="tableRowClassName">
      <el-table-column
        prop="id"
        label="ID"
        width="80">
      </el-table-column>
      <el-table-column
        prop="warningTime"
        label="预警时间"
        width="160">
      </el-table-column>
      <el-table-column
        prop="productName"
        label="产品名称">
      </el-table-column>
      <el-table-column
        prop="supplier"
        label="供应商">
      </el-table-column>
      <el-table-column
        prop="batch"
        label="批次号"
        width="100">
      </el-table-column>
      <el-table-column
        prop="type"
        label="预警类型"
        width="120">
        <template scope="scope">
          <el-tag
            :type="scope.row.type === '温度异常' ? 'danger' : 
                 scope.row.type === '湿度异常' ? 'warning' : 
                 scope.row.type === '保质期预警' ? 'primary' : 'info'">
            {{ scope.row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="value"
        label="当前值"
        width="100">
      </el-table-column>
      <el-table-column
        prop="threshold"
        label="阈值"
        width="100">
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100">
        <template scope="scope">
          <el-tag :type="scope.row.status === '未处理' ? 'danger' : 'success'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="action"
        label="操作"
        width="180">
        <template scope="scope">
          <el-button
            size="small"
            :plain="true"
            @click="handleDetail(scope.$index, scope.row)">详情</el-button>
          <el-button
            size="small"
            type="success"
            :plain="true"
            :disabled="scope.row.status === '已处理'"
            @click="handleProcess(scope.$index, scope.row)">处理</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-bar margin-t-15" v-show="pagination.total > 10">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        layout="total, prev, pager, next"
        :total="pagination.total">
      </el-pagination>
    </div>
    
    <!-- 预警处理对话框 -->
    <el-dialog title="处理预警" v-model="processDialogVisible" size="small">
      <el-form :model="processForm" label-width="120px" :rules="processRules" ref="processForm">
        <el-form-item label="预警ID">
          <span>{{ currentWarning.id }}</span>
        </el-form-item>
        <el-form-item label="产品名称">
          <span>{{ currentWarning.productName }}</span>
        </el-form-item>
        <el-form-item label="预警类型">
          <span>{{ currentWarning.type }}</span>
        </el-form-item>
        <el-form-item label="当前值/阈值">
          <span>{{ currentWarning.value }} / {{ currentWarning.threshold }}</span>
        </el-form-item>
        <el-form-item label="处理方式" prop="method">
          <el-select v-model="processForm.method" placeholder="请选择处理方式">
            <el-option label="调整环境条件" value="调整环境条件"></el-option>
            <el-option label="隔离产品" value="隔离产品"></el-option>
            <el-option label="报废处理" value="报废处理"></el-option>
            <el-option label="降级处理" value="降级处理"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入处理备注"
            v-model="processForm.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitProcess">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      // 搜索条件
      search: {
        type: '',
        keyword: '',
        page: 1
      },
      
      // 预警类型
      warningTypes: [{
        value: '',
        label: '全部类型'
      }, {
        value: 'temperature',
        label: '温度异常'
      }, {
        value: 'humidity',
        label: '湿度异常'
      }, {
        value: 'shelf_life',
        label: '保质期预警'
      }, {
        value: 'inventory',
        label: '库存预警'
      }],
      
      // 预警统计
      warningStats: {
        total: 0,
        unprocessed: 0,
        processed: 0
      },
      
      // 表格数据
      tableData: [],
      
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      
      // 处理对话框
      processDialogVisible: false,
      currentWarning: {},
      processForm: {
        method: '',
        remark: ''
      },
      processRules: {
        method: [
          { required: true, message: '请选择处理方式', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请输入处理备注', trigger: 'blur' }
        ]
      }
    }
  },
  
  created() {
    this.getWarningList();
  },
  
  methods: {
    // 获取预警列表
    async getWarningList() {
      try {
        const response = await axios.get('/api/warnings', {
          params: {
            page: this.pagination.currentPage,
            pageSize: this.pagination.pageSize,
            type: this.search.type,
            keyword: this.search.keyword
          }
        });
        
        this.tableData = response.data.items.map(item => ({
          id: item.id,
          warningTime: this.formatDateTime(item.alert_time),
          productName: item.product_name || '未知产品',
          supplier: item.supplier_name || '未知供应商',
          batch: item.batch_number || '未知批次',
          type: this.getWarningTypeLabel(item.alert_type),
          value: this.extractValueFromContent(item.alert_content),
          threshold: item.threshold_value ? item.threshold_value + this.getUnitByType(item.alert_type) : '未知',
          status: item.status === 'pending' ? '未处理' : '已处理',
          rawData: item // 保存原始数据以便查看详情
        }));
        
        this.pagination.total = response.data.total;
        
        // 更新统计信息
        if (response.data.stats) {
          this.warningStats = response.data.stats;
        }
      } catch (error) {
        console.error('获取预警列表失败:', error);
        this.$message.error('获取预警列表失败');
      }
    },
    
    // 获取预警类型标签
    getWarningTypeLabel(type) {
      const map = {
        'temperature': '温度异常',
        'humidity': '湿度异常',
        'shelf_life': '保质期预警',
        'inventory': '库存预警'
      };
      return map[type] || type;
    },
    
    // 从预警内容中提取值
    extractValueFromContent(content) {
      if (!content) return '未知';
      try {
        // 尝试提取数字值
        const match = content.match(/(\d+(\.\d+)?)/);
        if (match) return match[0];
        return '未知';
      } catch (e) {
        return '未知';
      }
    },
    
    // 根据预警类型获取单位
    getUnitByType(type) {
      const map = {
        'temperature': '°C',
        'humidity': '%',
        'shelf_life': '天',
        'inventory': '件'
      };
      return map[type] || '';
    },
    
    // 处理类型变化
    handleTypeChange() {
      this.pagination.currentPage = 1;
      this.getWarningList();
    },
    
    // 处理关键词变化
    handleKeywordChange() {
      this.pagination.currentPage = 1;
      this.getWarningList();
    },
    
    // 手动搜索
    handleSearch() {
      this.getWarningList();
    },
    
    // 刷新预警
    handleRefresh() {
      this.getWarningList();
    },
    
    // 导出报表
    async handleExport() {
      try {
        // 创建一个 a 标签用于下载
        const link = document.createElement('a');
        link.href = `/api/warnings/export?type=${this.search.type || ''}&keyword=${this.search.keyword || ''}`;
        link.target = '_blank';
        link.download = `预警记录_${new Date().toISOString().slice(0, 10)}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.$message.success('预警记录导出成功');
      } catch (error) {
        console.error('导出预警记录失败:', error);
        this.$message.error('导出预警记录失败');
      }
    },
    
    // 查看详情
    handleDetail(index, row) {
      // 这里可以展示更详细的信息，例如通过对话框
      this.$alert(
        `<div>
          <p><strong>预警ID：</strong>${row.id}</p>
          <p><strong>预警时间：</strong>${row.warningTime}</p>
          <p><strong>产品名称：</strong>${row.productName}</p>
          <p><strong>供应商：</strong>${row.supplier}</p>
          <p><strong>批次号：</strong>${row.batch}</p>
          <p><strong>预警类型：</strong>${row.type}</p>
          <p><strong>当前值：</strong>${row.value}</p>
          <p><strong>阈值：</strong>${row.threshold}</p>
          <p><strong>状态：</strong>${row.status}</p>
          <p><strong>预警内容：</strong>${row.rawData.alert_content || '无详细内容'}</p>
        </div>`,
        '预警详情',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '关闭'
        }
      );
    },
    
    // 处理预警
    handleProcess(index, row) {
      this.currentWarning = row;
      this.processForm = {
        method: '',
        remark: ''
      };
      this.processDialogVisible = true;
    },
    
    // 提交处理
    async submitProcess() {
      try {
        await this.$refs.processForm.validate();
        
        await axios.post(`/api/warnings/${this.currentWarning.id}/process`, {
          method: this.processForm.method,
          remark: this.processForm.remark
        });
        
        this.$message.success('预警处理成功');
        this.processDialogVisible = false;
        
        // 刷新预警列表
        this.getWarningList();
      } catch (error) {
        console.error('处理预警失败:', error);
        this.$message.error('处理预警失败: ' + ((error.response && error.response.data && error.response.data.error) || error.message));
      }
    },
    
    // 处理分页
    handleCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.getWarningList();
    },
    
    // 行样式
    tableRowClassName({row}) {
      if (row.status === '未处理') {
        return 'warning-row';
      }
      return '';
    },
    
    // 格式化日期时间
    formatDateTime(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    }
  }
}
</script>

<style scoped>
.page-comon-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.page-comon-header .left {
  display: flex;
  align-items: center;
}

.page-comon-header .right {
  display: flex;
}

.right-item {
  margin-left: 30px;
  min-width: 80px;
}

.page-search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.page-search-bar .left {
  display: flex;
  align-items: center;
}

.margin-r-5 {
  margin-right: 5px;
}

.font14 {
  font-size: 14px;
}

.font28 {
  font-size: 28px;
  font-weight: bold;
  display: block;
}

.txt-info {
  color: #909399;
}

.warning-text {
  color: #E6A23C;
}

.success-text {
  color: #67C23A;
}

.padding-b-10 {
  padding-bottom: 10px;
}

.margin-t-15 {
  margin-top: 15px;
}

.pagination-bar {
  text-align: right;
}

.warning-row {
  background-color: #fcf6ed;
}

.text-center {
  text-align: center;
}
</style> 